<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 表单筛选区 -->
      <div class="search-box">
        <!-- 控制表单水平排列 -->
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="文章分类">
            <el-select placeholder="请选择分类" v-model="query.cate_id">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章状态">
            <el-select placeholder="请选择状态" v-model="query.state">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="initArticle">查询</el-button>
            <el-button type="info" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="add-button" @click="dialogVisible = true"
          >添加文章</el-button
        >
      </div>
    </el-card>
    <el-dialog
      fullscreen
      title="发布文章"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form ref="addForm" label-width="80px" :model="addData" :rules="rules">
        <el-form-item label="文章标题" prop="title">
          <el-input placeholder="请输入标题" v-model="addData.title"></el-input>
        </el-form-item>
        <el-form-item label="选择分类" prop="cate_id">
          <el-select placeholder="请选择" style="width: 100%" v-model="addData.cate_id">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <quill-editor v-model="addData.content"> </quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <div>
            <img :src="imgurl" v-if="imgurl" class="cover-img" alt="" />
            <img src="@/assets/images/cover.jpg" v-else class="cover-img" alt="" />
          </div>
          <input type="file" ref="fileRef" style="display: none" @change="chooseImg" />
          <el-button type="text" @click="$refs.fileRef.click()">选择图片</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="publish('已发布')">发布</el-button>
          <el-button type="info" @click="publish('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 表格区 -->
    <el-table :data="artList" style="width: 100%" stripe border>
      <el-table-column prop="id" label="ID" width="180"> </el-table-column>
      <el-table-column prop="title" label="文章标题" width="180"> </el-table-column>
      <el-table-column prop="cate_name" label="所属分类"> </el-table-column>
      <el-table-column label="发布时间">
        <template v-slot="obj"> {{ obj.row.pub_date | date_format }} </template>
      </el-table-column>
      <el-table-column prop="state" label="文章状态"> </el-table-column>
      <el-table-column label="操作"> </el-table-column>
    </el-table>
    <!-- 分页区 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="query.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { getCategoryAPI } from '@/api/category'
import { addArtListAPI, getArticleListAPI } from '@/api/article'
import dayjs from 'dayjs'

export default {
  name: 'ArtList',
  data() {
    return {
      total: 0,
      dialogVisible: false,
      imgurl: '',
      // 分类列表数据
      cateList: [],
      addData: {
        title: '',
        content: '',
        cate_id: '',
        cover_img: '',
        state: ''
      },
      artList: [],
      query: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      rules: {
        title: [
          { required: true, message: '标题必填', trigger: 'blur' },
          { min: 1, max: 30, message: '标题长度1-30位', trigger: 'change' }
        ],
        cate_id: [
          { required: true, message: '必须选择一个分类', trigger: ['blur', 'change'] },
          {
            pattern: /^[1-9][0-9]*$/,
            message: '分类id必须是大于0的整数',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('此操作可能导致内容丢失', '提示', {
        type: 'warning',
        callback: r => {
          if (r === 'confirm') {
            this.dialogVisible = false
          }
        }
      })
      // done()  通过done方法关闭弹窗
      // this.dialogVisible = false
    },
    // 获取分类
    async initCategory() {
      const { data: res } = await getCategoryAPI()
      if (res.code === 0) {
        this.cateList = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    chooseImg(e) {
      if (e.target.files.length > 0) {
        this.addData.cover_img = e.target.files[0]
        this.imgurl = URL.createObjectURL(e.target.files[0])
      } else {
        this.addData.cover_img = ''
        this.imgurl = ''
      }
    },
    publish(s) {
      this.addData.state = s
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        if (this.addData.content === '') return this.$message.error('请输入内容')
        if (this.addData.cover_img === '') return this.$message.error('请选择图片')
        const fd = new FormData()

        for (const k in this.addData) {
          fd.append(k, this.addData[k])
        }
        const { data: res } = await addArtListAPI(fd)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$refs.addForm.resetFields()
          this.addData.content = ''
          this.addData.cover_img = ''
          this.imgurl = ''
          this.$refs.fileRef.value = ''
          this.dialogVisible = false
          // 重新获取渲染列表，后续再做
        } else {
          this.$message.error(res.message)
        }
      })
    },
    async initArticle() {
      const { data: res } = await getArticleListAPI(this.query)
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      } else {
        this.$message.error(res.message)
      }
    },
    // 每页条数改变后触发
    handleSizeChange(newSize) {
      this.query.pagesize = newSize
      this.query.pagenum = 1
      this.initArticle()
    },
    handleCurrentChange(newPage) {
      this.query.pagenum = newPage
      this.initArticle()
    },
    resetList() {
      this.query = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArticle()
    }
  },
  created() {
    this.initCategory()
    this.initArticle()
  },
  filters: {
    date_format(val) {
      return dayjs(val).format('YYYY-MM-DD hh:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.add-button {
  margin-top: 2px;
}
/deep/.ql-editor {
  height: 240px;
}
.cover-img {
  height: 280px;
  width: 400px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 20px;
}
</style>
